package com.exp3.virus.controller;

import com.exp3.virus.model.RegionStates;
import com.exp3.virus.service.CsvDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequiredArgsConstructor
public class VirusController {
    @Resource
    private final CsvDataService data;

    @RequestMapping("/")
    public String home(Model model, String country) {
        List<RegionStates> allStates;

        if (country==null)
            allStates = data.getAllRegionStates();

        else if(country!=null){
            if(country.equals("all"))
                allStates = data.getAllRegionStates();
            else
            allStates = data.getAllRegionStates()
                    .parallelStream()   //注意它是通过这种方法来过滤地址栏参数，从而进行搜索查找
                    .filter(RegionStates -> RegionStates.getCountry().equals(country))
                    .collect(Collectors.toList());  //显示出查找出的结果
        }
        else
            allStates = data.getAllRegionStates();

        //这两句要在外面才可以！
        model.addAttribute("RegionStatesLists", allStates);
        return "index";
    }

    @RequestMapping("/{cty}")
    public String home2(Model model, @PathVariable("cty") String country) {
        List<RegionStates> allStats;
        if(country == null || country.equals("all"))
            allStats=data.getAllRegionStates();

        else
            allStats=data.getAllRegionStates()
                    .parallelStream()
                    .filter(RegionStates->RegionStates.getCountry().equals(country))
                    .collect(Collectors.toList());

        model.addAttribute("RegionStatesLists", allStats);
        return "index";
    }

}
